/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.gate.service;

import org.cshoo.tattoo.gate.constant.AccessScope;
import org.cshoo.tattoo.gate.entity.Authority;
import org.cshoo.tattoo.gate.repository.IAuthorityRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 杨翼
 * @since 1.0
 */
@Service
public class AuthorityService {

    @Resource
    private IAuthorityRepository authorityRepository;

    /**
     * 检查一个uri是否属于拒绝访问范围
     *
     * @param method 方法
     * @param path 路径
     * @return 判断结果
     */
    public boolean checkDenyScope(String method, String path) {
        return checkByScope(method, path, AccessScope.DENY);
    }

    /**
     * 检查一个uri是否属于匿名访问范围
     *
     * @param method 方法
     * @param path   路径
     * @return 判断结果
     */
    public boolean checkAnonymousScope(String method, String path) {
        return checkByScope(method, path, AccessScope.ANONYMOUS);
    }

    /**
     * 检查一个uri是否为所有用户访问范围
     *
     * @param method 方法
     * @param path   path路径
     * @return 检查结果
     */
    public boolean checkEveryoneScope(String method, String path) {
        return checkByScope(method, path, AccessScope.EVERYONE);
    }

    /**
     * 判断是否属于某个accessScope
     *
     * @param method      方法
     * @param path        路径
     * @param accessScope 访问范围
     * @return 判断结果
     */
    private boolean checkByScope(String method, String path, AccessScope accessScope) {
        List<Authority> authorities = authorityRepository.findAuthoritiesByAccessScope(accessScope.getValue());
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (Authority authority : authorities) {
            if (StringUtils.endsWithIgnoreCase(authority.getMethod(), method) && antPathMatcher.match(authority.getUri(), path)) {
                return true;
            }
        }
        return false;
    }

}
